/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。
 * 
 * 欢迎到知启蒙网站（https://www.zhiqim.com）购买正版软件，知启蒙还提供许多开源框架和软件。
 * 
 * 1、本软件产品所有源代码受《中华人民共和国著作权法》和其他有关法律、法规的保护，其所有知识产权归湖南知启蒙科技有限公司所有；
 * 2、禁止复制和修改。不得复制修改、翻译或改编本软件所有源代码，或者基于本软件产品创作衍生作品；
 * 3、禁止进行逆向工程。不得对本软件的源代码进行逆向工程、反编译或试图以其他方式发现软件的源代码；
 * 4、个别授权：如需进行商业性的销售、复制、分发，包括但不限于软件销售、预装、捆绑等，必须获得知启蒙的书面授权和许可；
 * 5、保留权利：本注释未明示授权的其他一切权利仍归知启蒙所有，任何人使用其他权利时必须获得知启蒙的书面同意。
*/
package net.redxyz.repost.resource.action.schedule;

import java.util.List;

import net.redxyz.repost.resource.SessionUser;
import net.redxyz.top.TaobaoService;
import net.redxyz.top.data.item.Item;
import net.redxyz.top.message.item.ItemSellerGetResponse4_24625;
import net.redxyz.top.message.item.ItemSellerGetResponse4_24625_Sku;
import net.redxyz.top.repost.dbo.AssRepostSchedule;
import net.redxyz.top.repost.dbo.AssRepostScheduleTime;

import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.extend.GetPostAction;
import org.zhiqim.kernel.util.DateTimes;
import org.zhiqim.kernel.util.Ints;
import org.zhiqim.kernel.util.Validates;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Selector;

/**
 * 定时上下架修改
 *
 * @version v7.0.1 @author zouzhigang 2021-7-29 新建与整理
 */
public class RepostScheduleModifyAction extends GetPostAction
{
    @Override
    public void doGet(HttpRequest request) throws Exception
    {
        SessionUser sessionUser = request.getSessionUser(SessionUser.class);
        String nick = sessionUser.getNick();
        long numIid = request.getParameterLong("numIid");

        // 查上架计划
        AssRepostSchedule repost = ORM.table().item(AssRepostSchedule.class, nick, numIid);
        if (repost == null)
        {
            request.returnCloseDialog("请选择一个有效的宝贝");
            return;
        }

        // 查时间列表
        Selector selector = new Selector();
        selector.addMaybe("nick", nick);
        selector.addMaybe("numIid", numIid);
        selector.addOrderbyAsc("planTime");
        List<AssRepostScheduleTime> list = ORM.table().list(AssRepostScheduleTime.class, selector);

        request.setAttribute("repost", repost);
        request.setAttribute("list", list);

        // 查询是否有SKU
        ItemSellerGetResponse4_24625_Sku resp = TaobaoService.getItemService().getItemSku(sessionUser.getNick(), sessionUser.getSessionId(), numIid);
        if (!resp.isSuccess())
        {
            request.returnCloseDialog("查询宝贝SKU失败");
            return;
        }

        request.setAttribute("hasSku", Validates.isNotEmpty(resp.getSkus()));
    }

    public void doPost(HttpRequest request) throws Exception
    {
        long numIid = request.getParameterLong("numIid");
        int num = request.getParameterInt("num", 0);
        int planSchedule = request.getParameterInt("planSchedule");
        String planTypes = request.getParameter("planType");
        String planTimes = request.getParameter("planTime");

        String[] planTypeArr = planTypes.split(",");
        String[] planTimeArr = planTimes.split(",");

        SessionUser sessionUser = request.getSessionUser(SessionUser.class);
        String dateTime = DateTimes.getDateTimeString();
        String nick = sessionUser.getNick();

        ItemSellerGetResponse4_24625 resp = TaobaoService.getItemService().getItem(sessionUser.getNick(), sessionUser.getSessionId(), numIid);
        if (!resp.isSuccess())
        {
            request.returnHistory("宝贝不存在，请重新操作");
            return;
        }

        Item item = resp.getItem();

        // 计划时间
        String datetime = DateTimes.getDateTimeString().substring(0, 17) + "00";
        for (int i = 0; i < planTypeArr.length; i++)
        {
            if (!Validates.isDateTime(planTimeArr[i]))
            {
                request.returnHistory("请填写正确的时间格式");
                return;
            }

            String time = planTimeArr[i].substring(0, 17) + "00";
            if (time.compareTo(datetime) <= 0)
            {
                request.returnHistory("时间格式不能小于当前时间");
                return;
            }

            // 把秒数去掉放回数组中
            planTimeArr[i] = time;
        }

        // 重置计划
        AssRepostSchedule repostLoop = new AssRepostSchedule();
        repostLoop.setNick(nick);
        repostLoop.setNumIid(item.getNumIid());
        repostLoop.setTitle(item.getTitle());
        repostLoop.setNum(num);
        repostLoop.setPlanStatus(1);
        repostLoop.setPlanSchedule(planSchedule);
        repostLoop.setCreateTime(dateTime);
        repostLoop.setOuterId(item.getOuterId());
        repostLoop.setPicUrl(item.getPicUrl());
        ORM.table().replace(repostLoop);

        // 重置时间，先删除后加入
        ORM.table().delete(AssRepostScheduleTime.class, new Selector("nick", nick).addMaybe("numIid", numIid));
        for (int i = 0; i < planTypeArr.length; i++)
        {
            int planType = Ints.toInt(planTypeArr[i]);
            AssRepostScheduleTime repostTime = new AssRepostScheduleTime();
            repostTime.setNick(nick);
            repostTime.setNumIid(item.getNumIid());
            repostTime.setPlanTime(planTimeArr[i]);
            repostTime.setPlanType(planType);
            repostTime.setPlanHandleStatus(0);
            repostTime.setPlanHandleTime(null);
            repostTime.setPlanHandleDesc(null);

            ORM.table().replace(repostTime);
        }

        request.setRedirect("javascript:{alert('保存成功');parent.location.reload();}");
    }

    @Override
    protected void validate(HttpRequest request)
    {
        // TODO Auto-generated method stub

    }
}
